<?php
	include "setup.php";
	
	//header("Content-Type: image/jpeg");

	$path = urldecode($_GET['path']);
	$name = $_GET['name'];

	$photo_path = $tpg_config["prefix_photo_dir"].$path;

	$src = $photo_path . "/" . $name;
	$thum_src = $tpg_config["prefix_thum_dir"] . $path . "/" . $name;

	$result_src = "";
	if ($tpg_config["thumbnail"] == true) {
		$srcstat = @stat($src);
		$thumbstat = @stat($thum_src);
	
		// 썸네일 생성
		if ($srcstat["mtime"] != $thumbstat["mtime"]) {
			@unlink($thum_src);
	
			$size = getImagesize($src);
			$width = $size[0];
			$height = $size[1];
			if ($width > $height) {
				$height = $height/($width/$tpg_config["thumbnail_size"]);
				$width = $tpg_config["thumbnail_size"];
			}elseif ($width < $height) {
				$width = $width/($height/$tpg_config["thumbnail_size"]);
				$height = $tpg_config["thumbnail_size"];
			}else{
				$width = $height = $tpg_config["thumbnail_size"];
			}
			$src_img = imagecreatefromjpeg($src);
			$dest_img = imagecreatetruecolor($width,$height);
			imagecolorallocate($dest_img,0,0,0); // White Background
			imagecopyresampled($dest_img,$src_img,0,0,0,0,$width,$height,$size[0],$size[1]);
			@imagejpeg($dest_img,$thum_src);
			@imagedestroy($dest_img);
			@imagedestroy($src_img);
	
			@touch($thum_src,$srcstat["mtime"]);
			
			// 파일이 정상적으로 생성됬는지 체크
			if (is_file($thum_src)) {
				$result_src = $thum_src;
			}else{
				$result_src = $src;
			}
		}else{
			$result_src = $thum_src;
		}
	}else{
		$result_src = $src;
	}

	//echo $thum_src;
	$file_ext = strtolower(substr($result_src,strrpos ($result_src,".")+1));
	
	if (trim($file_ext)=="" ) exit();
	
	switch ($file_ext) {
		case "pdf": $ctype="application/pdf"; break;
		case "gif": $ctype="image/gif"; break;
		case "png": $ctype="image/png"; break;
		case "jpeg":
		case "jpg": $ctype="image/jpeg"; break;
		default: exit();
	}
	
	header("Pragma: public");
	header("Expires: 0");
	header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
	header("Cache-Control: private",false);
	header("Content-Type: $ctype");
	header("Content-Disposition: attachment; filename=\"".basename($name)."\";");
	header("Content-Transfer-Encoding: binary");
	header("Content-Length: ".@filesize($result_src));
	readfile($result_src);
?>